import re

import koji, os, sys, requests

pwd = os.path.dirname(os.path.realpath(__file__))
sys.path.append(pwd + '../')
os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'riscv_build_dataset.settings')

import django

django.setup()

from fedora.models import koji_package, koji_build
from config import BASE_URL
from tqdm import tqdm

session = koji.ClientSession(f'{BASE_URL}/kojihub')


def get_build(nvr):
    try:
        build_info = session.getBuild(nvr)
        # print(build_info)
    except Exception as e:
        print(e, file=sys.stderr)

    return build_info


def get_build_log(nvr):
    log_url = f'{BASE_URL}/kojifiles/'
    try:
        # Get log list
        logs = session.getBuildLogs(nvr)
        # print(logs)
        # Get log file
        # for log in logs:
        #     url = f'{log_url}{log["path"]}'
        #     resp = requests.get(url)
        #     print(resp.text)
    except Exception as e:
        print(e, file=sys.stderr)

    return logs


def list_builds(package_name: str):
    try:
        builds = session.listBuilds(packageID=package_name)
        # print(*builds, sep='\n')
        # print(builds)
    except Exception as e:
        print(e, file=sys.stderr)
    return builds


def list_all_builds():
    print('Fetching all builds, this may take long time...')
    try:
        builds = session.listBuilds()
    except Exception as e:
        print(e, file=sys.stderr)
    return builds


def save_builds_to_db(builds: list):
    lst = []
    for b in tqdm(builds):
        nvr = b.get('nvr')
        tag = re.findall("fc\d{2}", nvr)
        if tag:
            tag = tag[-1]
        else:
            tag = None
        tmp = koji_build(
            build_id=b.get('build_id'),
            package_id=b.get('package_id'),
            package_name=b.get('package_name'),
            name=b.get('name'),
            version=b.get('version'),
            release=b.get('release'),
            nvr=nvr,
            owner_id=b.get('owner_id'),
            owner_name=b.get('owner_name'),
            state=b.get('state'),
            source=b.get('source'),
            task_id=b.get('task_id'),
            completion_time=b.get('completion_ts'),
            creation_time=b.get('creation_ts'),
            start_time=b.get('start_ts'),
            tag=tag
        )
        lst.append(tmp)
    print('Saving builds to DB...')
    koji_build.objects.bulk_create(lst, update_conflicts=True, update_fields=['tag'], batch_size=10000)


def save_all_builds_to_db():
    prefixs = '0123456789abcdefghijklmnopqrstuvwxyz'
    for l in tqdm(prefixs):
        print(f'Fetching build with prefix={l}')
        try:
            builds = session.listBuilds(prefix=l)
            lst = []
            for b in builds:
                nvr = b.get('nvr')
                tag = re.findall("fc\d{2}", nvr)
                if tag:
                    tag = tag[-1]
                else:
                    tag = None
                tmp = koji_build(
                    build_id=b.get('build_id'),
                    package_id=b.get('package_id'),
                    package_name=b.get('package_name'),
                    name=b.get('name'),
                    version=b.get('version'),
                    release=b.get('release'),
                    nvr=nvr,
                    owner_id=b.get('owner_id'),
                    owner_name=b.get('owner_name'),
                    state=b.get('state'),
                    source=b.get('source'),
                    task_id=b.get('task_id'),
                    completion_time=b.get('completion_ts'),
                    creation_time=b.get('creation_ts'),
                    start_time=b.get('start_ts'),
                    tag=tag
                )
                lst.append(tmp)
            print('Saving builds to DB...')
            koji_build.objects.bulk_create(lst, update_conflicts=True, update_fields=['tag'], batch_size=10000)
        except Exception as e:
            print(e, file=sys.stderr)
            print(f'Error while getting prefix={l}, skipping...', file=sys.stderr)


if __name__ == '__main__':
    # builds = list_all_builds()
    # save_builds_to_db(builds)
    save_all_builds_to_db()
    exit(0)

    nvr = {
        'name': 'gcc',
        'version': '14.0.1',
        'release': '0.7.0.riscv64.fc40'
    }
    # build = get_build(nvr)
    # log = get_build_log(nvr)
    builds = list_builds('gcc')
    save_builds_to_db(builds)
    # nvr_list = [build['nvr'] for build in builds]
    # print(nvr_list)
